let heartbeatTimer: number = 0;

export const socket = {
	ttSocket: null,
	wsUrl: "",
	loading: false,
	count: 1,
	init(url: string, token: string) {
		// const tokenUrl = url + '?token=' + token
		socket.wsUrl = url
		socket.connect(url)
	},
	connect(url: string) {
		if (socket.loading) {
			return
		}
		socket.loading = true
		socket.ttSocket = uni.connectSocket({
			url: url,
			success: () => {
				socket.loading = false
				// #ifdef MP-TOUTIAO
				console.log('MP-TOUTIAO')
				uni.showToast({
					title: '进入房间成功',
					icon: 'none'
				})
				setTimeout(() => {
					socket.onMessage()
					setTimeout(() => {
						if (uni.getStorageSync('token')) {
							socket.send(JSON.stringify({
								type: 'userRegister',
								token: uni.getStorageSync('token')
							}), () => {
								uni.$emit('onRegister')
							})
						}
					}, 2000)
				}, 2000)
				// #endif
			},
			fail: (err) => {
				console.log('打开失败');
				console.log(err);
				setTimeout(() => {
					socket.loading = false
					socket.connect(url)
				}, 2000)
			}
		})
		// #ifdef MP-TOUTIAO
		socket.ttSocket.onClose(() => {
			uni.showToast({
				title: '通讯已被关闭，请重启APP',
				icon: 'none'
			})
		})
		// #endif
		// #ifndef MP-TOUTIAO
		uni.onSocketOpen(function () {
			socket.count = 1
			uni.showToast({
				title: '进入房间成功',
				icon: 'none'
			})
			socket.onMessage()
			if (uni.getStorageSync('token')) {
				socket.send(JSON.stringify({
					type: 'userRegister',
					token: uni.getStorageSync('token')
				}), () => {
					uni.$emit('onRegister')
				})
			}

			// 开启心跳定时器，间隔为30s
			heartbeatTimer = setInterval(function () {
				socket.send(JSON.stringify({
					type: 'ping'
				}))
			}, 30000);
		});
		uni.onSocketError(function () {
			clearInterval(heartbeatTimer);
			console.log('WebSocket连接打开失败，请检查！');
			setTimeout(() => {
				if (socket.count < 5) {
					console.log(`通讯连接失败，正在尝试第${socket.count}次重连...`);
					uni.showToast({
						title: `通讯连接失败，正在尝试第${socket.count}次重连...`,
						icon: 'none'
					})
					socket.count++
					socket.connect(socket.wsUrl)
				} else {
					uni.closeSocket()
				}
			}, 3000)
		});
		uni.onSocketClose(function () {
			clearInterval(heartbeatTimer);
			console.log('WebSocket 已关闭！');
			uni.showToast({
				title: '通讯已被关闭，请重启APP',
				icon: 'none'
			})
			setTimeout(() => {
				if (socket.count < 6) {
					console.log(`通讯连接失败，正在尝试第${socket.count}次重连...`);
					socket.count++
					socket.connect(socket.wsUrl)
				}
			}, 3000)
		});
		// #endif
	},
	onMessage() {
		console.log('onMessage')
		// #ifdef MP-TOUTIAO
		socket.ttSocket.onMessage((res: any) => {
			uni.$emit('receivedMsgCallBack', res.data)
		})
		// #endif
		// #ifndef MP-TOUTIAO
		uni.onSocketMessage((res: any) => {
			console.log(res);
			uni.$emit('receivedMsgCallBack', res.data)
		})
		// #endif
	},
	send(data: string, callback: any = '') {
		// #ifdef MP-TOUTIAO
		socket.ttSocket.send({
			data
		})
		// #endif
		// #ifndef MP-TOUTIAO
		uni.sendSocketMessage({
			data,
			complete: () => {
				if (callback) {
					setTimeout(() => {
						callback()
					}, 500)
				}
			}
		})
		// #endif
	}
}